package com.sc.justification.component;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

import com.google.gson.Gson;
import com.sc.justification.word.WordProcessor;

public class WebPanel extends JPanel {
	private String templateName = null;
	private WordProcessor wordProcessor = null;;
	private JWebBrowser webBrowser=null;
        public WebPanel(){
            super();
        }
	public WebPanel(String templateName) {

		super(new BorderLayout());
		this.templateName = templateName;
		webBrowser = new JWebBrowser();
		webBrowser.setStatusBarVisible(false);
		webBrowser.setLocationBarVisible(true);
		webBrowser.setMenuBarVisible(false);
		webBrowser.setBarsVisible(false);
		webBrowser.navigate("file://" + Constants.PAGE_DIR + templateName
				+ ".htm");
		add(webBrowser, BorderLayout.CENTER);
		//
		wordProcessor = new WordProcessor(Constants.TEMPLATE_DIR + templateName
				+ ".docx");
		JPanel actionBar = new JPanel();
		add(actionBar, BorderLayout.SOUTH);
		JButton expBtn = new JButton("������word");
		actionBar.add(expBtn);
		expBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String json = (String) webBrowser
						.executeJavascriptWithResult("return getData();");
				Gson gson = new Gson();
				Map<String, String> data = (Map<String, String>) gson.fromJson(
						json, Map.class);
				final String outputFile = Constants.DOC_DIR
						+ WebPanel.this.templateName + ".docx";

				wordProcessor.write(data, outputFile);

				SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
					private String jsCall = null;

					@Override
					protected Void doInBackground() throws Exception {
						File file = new File(outputFile);
						long lastmodified = file.lastModified();
						System.out.println(lastmodified);
						boolean b = true;
						while (b) {
							long lastmodified2 = file.lastModified();
							System.out.println(lastmodified2);
							if (lastmodified2 > lastmodified) {
								b = false;
								lastmodified = lastmodified2;
								Map<String, String> data = wordProcessor
										.read(outputFile);
								Gson gson = new Gson();
								String dataStr = gson.toJson(data);
								System.out.println(dataStr);
								 jsCall = webBrowser
										.createJavascriptFunctionCall(
												"setData", dataStr);
								

							} else {
								Thread.sleep(1000);
							}
						}
						return null;
					}

					@Override
					protected void done() {
						webBrowser.executeJavascript(jsCall);
					}
				};
				swingWorker.execute();
			}
		});
	}
}
